package com.ywk.swagger.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

/**
 * 参考链接：https://cloud.tencent.com/developer/article/2235266?areaSource=102001.10&traceId=PtbQikEUwhv192sISxuis
 *
 * @Author zbh
 * @Date 2023/7/11
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi(Environment environment){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("系统接口")
                .enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ywk.swagger.business.controller"))
                //加了ApiOperation注解的类，才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build()
                /*.securitySchemes(securitySchemes())
                .securityContexts(securityContexts())*/;

    }

    /**
     *
     * @return
     */
    private ApiInfo apiInfo(){
        return  new ApiInfoBuilder()
                .title("Spring Boot 中使用Swagger2 构建RestFul Api")
                .description("这是 description 描述")
                .termsOfServiceUrl("https://gitee.com/zbh-ywk/")
                .contact(new Contact("YWK","localhost:8088/swagger-ui.html（使用Knife4j插件：http://localhost:8088/doc.html）","1468361098@qq.com"))
                .version("1")
                .build();
    }

    /**
     * 设置token相关的请求头为X-AUTH-TOKEN
     */
    private List<SecurityScheme> securitySchemes() {
        ApiKey apiKey = new ApiKey("X-AUTH-TOKEN", "X-AUTH-TOKEN", In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    /**
     * 授权信息全局应用
     */
    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(Collections.singletonList(new SecurityReference("X-AUTH-TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
                        .build()
        );
    }
}
